package com.ics.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ics.admin.domain.Building;
import com.ics.admin.domain.Customer;
import com.ics.admin.domain.Park;
import com.ics.admin.domain.Room;
import com.ics.admin.service.*;
import com.ics.common.constant.Constants;
import com.ics.common.core.controller.BaseController;
import com.ics.common.core.domain.IcsCustomerStaff;
import com.ics.common.core.domain.R;
import com.ics.common.core.text.Convert;
import com.ics.common.utils.ValidatorUtils;
import com.ics.common.utils.http.HttpUtils;
import com.ics.system.domain.Tenant;
import com.ics.system.domain.User;
import com.ics.system.service.ITenantService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.RequiresPermissions;
import org.wf.jwtp.util.SubjectUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 客户管理 提供者
 *
 * @author zzm
 * @date 2020-10-16
 */
@RestController
@RequestMapping("admin/customer")
public class CustomerController extends BaseController {

    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IIcsCustomerStaffService icsCustomerStaffService;

    @Autowired
    private IParkService parkService;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IBuildingService buildingService;

    /**
     * app的key值
     */
    @Value("${qixin.appKey}")
    private String appKey;

    /**
     * app的密钥值
     */
    @Value("${qixin.secretKey}")
    private String secretKey;

    /**
     * url
     */
    @Value("${qixin.url}")
    private String url;


    /**
     * 调用启信api获取企业照面
     */
    @RequiresPermissions("admin:customer:view")
    @PostMapping("getBasicInfo")
    public R getQiXinBasicInfo(String keyword) {
        String qiXinBasicInfo = HttpUtils.sendGet(url, "appkey=" + appKey + "&secret_key=" + secretKey + "&keyword=" + keyword);
        JSONObject result = (JSONObject) JSON.parse(qiXinBasicInfo);
        // 启信宝的接口返回成功码-200
        String SUCCESS_CODE = "200";
        if (result != null) {
            String status = result.get("status").toString();
            if (SUCCESS_CODE.equals(status)) {
                return R.data(result.get("data").toString());
            } else {
                return R.error(result.get("message").toString());
            }
        }
        return R.error("无当前企业数据！");
    }

    /**
     * 查询${tableComment}
     */
    @RequiresPermissions("admin:customer:view")
    @GetMapping("get/{id}")
    public Customer get(@PathVariable("id") Long id) {

        Customer customer = customerService.selectCustomerById(id);

        String roomId = customer.getRoomId();
        List<String> roomIds = StrUtil.split(roomId, ',');

        List<Long> collect = roomIds.stream().map(item -> Long.valueOf(item)).collect(Collectors.toList());
        customer.setRoomIds(collect);
        String buildId = customer.getBuildId();
        List<String> buildIds = StrUtil.split(buildId, ',');
        List<Long> collect1 = buildIds.stream().map(Long::valueOf).collect(Collectors.toList());
        customer.setBuildingDetailIds(collect1);
        return customer;

    }

    /**
     * 查询客户管理列表
     */
    @RequiresPermissions("admin:customer:list")
    @GetMapping("list")
    public R list(Customer customer) {
        startPage();
        customer.setDeleteFlag(0);

        System.out.println(this.getLoginCustomerId());
//        this.get
        boolean isAdmin = SubjectUtil.hasRole(getRequest(),"admin");
        if (isAdmin){
            customer.setCustomerId(Long.valueOf(this.getLoginCustomerId()));
        }
        List<Customer> customers = customerService.selectCustomerList(customer);

        for (Customer customer1 : customers) {
            Long tenantId = customer1.getTenantId();
            Tenant tenant = tenantService.selectTenantById(tenantId);
            customer1.setTenantName(tenant.getName());
            Building building = buildingService.selectBuildingById(customer1.getBuildingId());
            if (null != building){
                customer1.setBuildingName(building.getBuildingName());
            }

        }
        return result(customers);
    }

    /**
     * 合同查询客户管理列表
     */
    @RequiresPermissions("admin:customer:list")
    @GetMapping("allList")
    public R allList(Customer customer) {
        List<Customer> customerList = customerService.selectCustomerList(customer);

        List<Map> customerMaps = Lists.newArrayList();
        for (Customer item : customerList) {

            Map<String, Object> customerMap = Maps.newHashMap();
            getCustomerMap(customerMap, item);
            customerMaps.add(customerMap);
        }
        return R.data(customerMaps);
    }


    /**
     * 合同根据客户id查询客户部分信息
     */
    @RequiresPermissions("admin:customer:view")
    @GetMapping("findByCustomerId")
    public R findByCustomerId(Long customerId) {
        Map<String, Object> customerMap = Maps.newHashMap();
        Customer customer = customerService.selectCustomerById(customerId);
        getCustomerMap(customerMap, customer);
        return R.data(customerMap);
    }

    /**
     * 合同获取客户的部分信息
     */
    private void getCustomerMap(Map<String, Object> customerMap, Customer customer) {
        customerMap.put("id", customer.getId());
        customerMap.put("name", customer.getName());
        customerMap.put("sector", customer.getSector());
        customerMap.put("creditNo", customer.getCreditNo());
        customerMap.put("mail", customer.getMailAddress());
        customerMap.put("operName", customer.getOperName());
        customerMap.put("phone", customer.getPhone());
        customerMap.put("address", customer.getAddress());
        customerMap.put("channelName", customer.getChannelName());
    }


    /**
     * 新增保存客户管理
     */
    @RequiresPermissions("admin:customer:add")
    @PostMapping("save")
    public R addSave(@RequestBody Customer customer) {
//        if (User.isAdmin(getCurrentUserId())) {
//            return R.error("不允许超级管理员用户新增");
//        }


        //房间转成逗号隔开
        List<Long> buildingDetailIds = customer.getBuildingDetailIds();

        String buildIds = CollUtil.join(buildingDetailIds, ",");

        customer.setBuildId(buildIds);
        List<Long> roomIds = customer.getRoomIds();

        String roomids = CollUtil.join(roomIds, ",");
        customer.setRoomId(roomids);

        customer.setParkId(customer.getParkId());
        customer.setTenantId(customer.getTenantId());
        ValidatorUtils.validateEntity(customer);
        customer.setCreateBy(getLoginName());
        int i = customerService.insertCustomer(customer);
        //如果新增成功，把房间的状态改为已启用
        for (Long roomId : roomIds) {
            Room room = roomService.selectRoomById(roomId);
            room.setStatus(Room.Status.YES);
            int i1 = roomService.updateRoom(room);
            Assert.isTrue(i1 > 0, "修改房间已租状态失败");
        }



        return toAjax(i);
    }

    /**
     * 修改保存客户管理
     */
    @RequiresPermissions("admin:customer:edit")
    @PostMapping("update")
    public R editSave(@RequestBody Customer customer) {
        ValidatorUtils.validateEntity(customer);
        customer.setUpdateBy(getLoginName());

        //房间转成逗号隔开
        List<Long> buildingDetailIds = customer.getBuildingDetailIds();

        String buildIds = CollUtil.join(buildingDetailIds, ",");

        customer.setBuildId(buildIds);
        List<Long> roomIds = customer.getRoomIds();

        String roomids = CollUtil.join(roomIds, ",");
        customer.setRoomId(roomids);

        //如果新增成功，把房间的状态改为已启用
        for (Long roomId : roomIds) {
            Room room = roomService.selectRoomById(roomId);
            if (null != room){
                room.setStatus(Room.Status.YES);
                int i1 = roomService.updateRoom(room);
                Assert.isTrue(i1 > 0, "修改房间已租状态失败");
            }
        }
        //todo  修改成功后需要把里面的用户添加对应的设备

        return toAjax(customerService.updateCustomer(customer));
    }

    /**
     * 删除${tableComment}
     */
    @RequiresPermissions("admin:customer:remove")
    @PostMapping("remove")
    public R remove(String ids) {
        return toAjax(customerService.deleteCustomerByIds(ids));
    }


    /**
     * 查询访客列表
     * @param icsCustomerStaff
     * @return
     */
    @RequiresPermissions("admin:customer:visit")
    @GetMapping("visitList")
    public R visitList(IcsCustomerStaff icsCustomerStaff) {
        startPage();
        icsCustomerStaff.setDataType(Constants.CUSTOMER_VISIT);
        return result(icsCustomerStaffService.selectIcsCustomerStaffList(icsCustomerStaff));
    }

    /**
     * 查询企业员工列表
     * @param icsCustomerStaff
     * @return
     */
    @RequiresPermissions("admin:customer:staff")
    @GetMapping("staffList")
    public R staffList(IcsCustomerStaff icsCustomerStaff) {
        startPage();
        icsCustomerStaff.setDataType(Constants.CUSTOMER_STAFF);
        return result(icsCustomerStaffService.selectIcsCustomerStaffList(icsCustomerStaff));
    }

}
